package com.example.redislock;

import com.google.common.collect.Lists;
import redis.clients.jedis.Jedis;

import java.util.Collections;

public class RedisLock implements RedisDistributeLock {
    private static final String LOCK_SUCCESS = "OK";
    private static final Long RELEASE_LOCK = 1L;
    private static final Long POSTPONE_LOCK = 1L;
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "EX";
    private static final Long RELEASE_SUCCESS = 1L;

    @Override
    public Boolean lock(Jedis jedis, String lockKey, String requestId, int expireTime) {
        /**
         * 尝试获取分布式锁
         * @param jedis Redis客户端
         * @param lockKey 锁
         * @param requestId 请求标识
         * @param expireTime 超期时间
         * @return 是否获取成功
         *
         * 该set方法是原子操作，不会出现并发问题
         * 如果程序执行过程中，时间到期了，需要设置守护进程进行续命
         */

        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

        if (LOCK_SUCCESS.equals(result)) {
            //如果加锁成功，启动一个延时线程，防止业务逻辑为执行完就因锁超时而释放锁
            PostponeTask postponeTask = new PostponeTask(lockKey, requestId, expireTime, true, this, jedis);
            Thread thread = new Thread(postponeTask);
            thread.setDaemon(true);
            thread.start();
        }

        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean unLock(Jedis jedis, String lockKey, String requestId) {

        /**
         * 释放分布式锁
         * @param jedis Redis客户端
         * @param lockKey 锁
         * @param requestId 请求标识
         * @return 是否释放成功
         *
         * eval原子操作，不会出现想del那种删除错误问题，会导致任何客户端都可以随时进行解锁，即使这把锁不是它的
         */
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

        if (RELEASE_LOCK.equals(result)) {
            return true;
        }
        return false;
    }

    /**
     * 锁延时，防止执行业务未完成就释放锁了
     *
     * @param jedis
     * @param key
     * @param value
     * @param expireTime  延时时间  传过来的就是上锁的时间
     * @return
     */
    @Override
    public Boolean postpone(Jedis jedis, String key, String value, long expireTime) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1],ARGV[2]) else return '0' end";
        Object result = jedis.eval(script, Collections.singletonList(key), Lists.newArrayList(value,String.valueOf(expireTime)));
        if (POSTPONE_LOCK.equals(result)) {
            return true;
        }
        return false;
    }
}
